package org.example.utils;

import com.google.gson.Gson;
import org.example.Entity.CommodityMapRecognition;

import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;


public class GsonUtil {

    private static Gson gson = new Gson();

    public static String gsonToJSon(Object o){
        String s = gson.toJson(o);
        return s;
    }

    public static Map<String,Object> jsonToMap(String jsonStr){
        Map<String,Object> paramMap = gson.fromJson(jsonStr, HashMap.class);
        // 后处理：将Double类型的整数值转换为Integer
        for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
            if (entry.getValue() instanceof Double) {
                Double value = (Double) entry.getValue();
                entry.setValue(value.intValue()); // 转换为Integer
            }
        }
        return paramMap;
    }
    public static Object[] jsonToArray(String json, Type typeof){
        Object[] objects = gson.fromJson(json, typeof);
        return objects;
    }

    public static Object jsonToObject(String json, Type typeof){
        Object object = gson.fromJson(json, typeof);
        return object;
    }

    public static void main(String[] args) {
        String json = "{\"predicted_label\": \"Carrots\", \"scores\": [[\"Carrots\", \"0.152\"], [\"Tropicana-Golden-Grapefruit\", \"0.098\"], [\"Orange\", \"0.076\"], [\"Watermelon\", \"0.063\"], [\"Royal-Gala\", \"0.046\"]]}";
        CommodityMapRecognition o = (CommodityMapRecognition) jsonToObject(json, CommodityMapRecognition.class);
        System.out.println(o);
    }
}
